//
//  YJ_LoginViewController.m
//  YouJoin
//
//  Created by MacBookPro on 15/11/4.
//  Copyright © 2015年 MacBookPro. All rights reserved.
//  登录界面

#import "YJ_LoginController.h"
#import "YJ_LoginViewTextField.h"
#import "YJ_userInfo.h"
#import "AppDelegate.h"
#import "YJ_SignUpViewController.h"

@interface YJ_LoginController ()<NSURLConnectionDataDelegate>
@property (nonatomic,weak) YJ_LoginViewTextField *unF;
@property (nonatomic,weak) YJ_LoginViewTextField *pswF;
@property (nonatomic,weak) UIButton *signUpBtn;
@property (nonatomic,weak) UIButton *loginBtn;
@property(nonatomic,weak) UIActivityIndicatorView *activity ;
@property(nonatomic,weak) AppDelegate *appDelegate;
//服务器收到的data
@property (nonatomic, strong) NSMutableData *data;

@end

@implementation YJ_LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    // Do any additional setup after loading the view from its nib.
    
    //backgroundImage setting
    UIImageView *backgroundImage = [[UIImageView alloc]init];
    backgroundImage.image = [UIImage imageNamed:@"login_background"];
    backgroundImage.frame = self.view.frame;
    
    [self.view addSubview:backgroundImage];
    
    //textField setting
    YJ_LoginViewTextField *userNameField = [[YJ_LoginViewTextField alloc]init];
    self.unF = userNameField;
    CGFloat unfX = 0;
    CGFloat unfY = 220;
    CGFloat unfW = 320;
    CGFloat unfH = 50;
    userNameField.placeholder = @"username";
    userNameField.textAlignment = NSTextAlignmentCenter;
    userNameField.clearButtonMode = UITextFieldViewModeAlways;
    userNameField.frame = CGRectMake(unfX, unfY, unfW, unfH);
    [userNameField setValue:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.2] forKeyPath:@"_placeholderLabel.textColor"];
//    userNameField.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:userNameField];
    
    //pswField setting
    YJ_LoginViewTextField *passWordField = [[YJ_LoginViewTextField alloc]init];
    self.pswF = passWordField;
    CGFloat pswX = 0;
    CGFloat pswY = 220+unfH+1;
    CGFloat pswW = 320;
    CGFloat pswH = 50;
    passWordField.placeholder = @"password";
    passWordField.textAlignment = NSTextAlignmentCenter;
    passWordField.secureTextEntry = YES;
    passWordField.clearButtonMode = UITextFieldViewModeAlways;
    [passWordField setValue:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.2] forKeyPath:@"_placeholderLabel.textColor"];
    passWordField.frame = CGRectMake(pswX, pswY, pswW, pswH);
    [self.view addSubview:passWordField];

    //loginBtn setting
    UIButton *loginBtn = [[UIButton alloc]init];
    self.loginBtn = loginBtn;
//    loginBtn.backgroundColor = [UIColor redColor];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"login_loginBtn"]
                        forState:UIControlStateNormal];
    [loginBtn setTitle:@"login" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    loginBtn.titleLabel.textColor = [UIColor whiteColor];
    loginBtn.frame = CGRectMake(180, pswY+pswH+25, 74, 32);
    [self.view addSubview:loginBtn];
    [loginBtn addTarget:self action:@selector(toughloginBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //pswBtn setting
    UIButton *signUpBtn = [[UIButton alloc]init];
    self.signUpBtn = signUpBtn;
    //    loginBtn.backgroundColor = [UIColor redColor];
    [signUpBtn setBackgroundImage:[UIImage imageNamed:@"login_signUpBtn"]
                        forState:UIControlStateNormal];
    [signUpBtn setTitle:@"sign up" forState:UIControlStateNormal];
    signUpBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    signUpBtn.titleLabel.textColor = [UIColor whiteColor];
    signUpBtn.frame = CGRectMake(60, pswY+pswH+25, 74, 32);
    [self.view addSubview:signUpBtn];
    [signUpBtn addTarget:self action:@selector(touchSignUpBtn) forControlEvents:UIControlEventTouchUpInside];
    self.navigationController.navigationBarHidden = YES;
}

//-(BOOL)textFieldShouldReturn:(UITextField *)textField{
//    
//    [textField resignFirstResponder];
//    
//    return YES;
//    
//}

-(void)testLogin{
    [self performSegueWithIdentifier:@"segueToMainBarController" sender:self];
}

//点击登录按钮
-(void)toughloginBtn:(UIButton*) btn
{
//    [self testLogin];
    
    btn.hidden = YES;
    
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] init];
    [activity setCenter:CGPointMake(btn.frame.origin.x+btn.frame.size.width/2, btn.frame.origin.y+btn.frame.size.height/2)];//指定进度轮中心点
    
    [activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];//设置进度轮显示类型
    self.activity = activity;
    [self.view addSubview:activity];
    [activity startAnimating];
    
    [self loginCherk];

}

//登录检查并获取数据
-(void)loginCherk
{
    //设置url
    NSURL *url = [NSURL URLWithString:LOGINURL];
    //设置请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    
    //获取数据
    NSString *str = [NSString stringWithFormat: @"user_name=%@&user_password=%@",self.unF.text,self.pswF.text];
    
    NSLog(@"%@",str);
    
    //设置请求的字符串（数据）和编码格式
    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    //建立异步请求链接
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
    {
        
        //链接正常
        if (connectionError == NULL)
        {
            //            NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            //新建数据字典
            NSMutableDictionary *loginDict = [[NSMutableDictionary alloc]init];
            //json转字典
            loginDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            //向全局变量赋值
            self.appDelegate.userInfo = [YJ_userInfo initWithDict:loginDict];
            NSLog(@"%@",self.appDelegate.userInfo);
            

            //登录失败
            if([self.appDelegate.userInfo.result isEqualToString: @"failure"])
            {
                [[NSOperationQueue mainQueue]addOperationWithBlock:^
                {
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"用户名或密码错误" message:@"登录失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [alertView show];
                    self.loginBtn.hidden = NO;
                    [self.activity stopAnimating];
                }];
            }
            //服务器忙
            else if([self.appDelegate.userInfo.result isEqualToString: @"fail_serverbusy"])
            {
                [[NSOperationQueue mainQueue]addOperationWithBlock:^
                 {
                     UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"服务器忙，请稍后再试" message:@"登录失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                     [alertView show];
                     self.loginBtn.hidden = NO;
                     [self.activity stopAnimating];
                 }];
            }
            //登录成功
            else if([self.appDelegate.userInfo.result isEqualToString:@"success"])
            {
                [[NSOperationQueue mainQueue]addOperationWithBlock:^
                 {
                     self.loginBtn.hidden = NO;
                     [self.activity stopAnimating];
                     [self performSegueWithIdentifier:@"segueToMainBarController" sender:self];
                 }];
            }
        }
    }];
}

-(void)touchSignUpBtn
{
    YJ_SignUpViewController *signUpController = [[YJ_SignUpViewController alloc]init];
    [self presentViewController:signUpController animated:YES completion:nil];
    if([self.appDelegate.userInfo.result isEqualToString:@"success"]){
        [self performSegueWithIdentifier:@"segueToMainBarController" sender:self];
    }
}

#pragma mark - NSURLConnectionDataDelegate代理方法
#pragma mark 接受到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 准备工作
    // 按钮点击就会有网络请求,为了避免重复开辟空间
    if (!self.data) {
        self.data = [NSMutableData data];
    } else {
        [self.data setData:nil];
    }
}

#pragma mark 接收到数据,如果数据量大,例如视频,会被多次调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 拼接数据,二进制流的体现位置
    [self.data appendData:data];
}

#pragma mark 接收完成,做最终的处理工作
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 最终处理
    NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@ %@", str, [NSThread currentThread]);
}

#pragma mark 出错处理,网络的出错可能性非常高
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error.localizedDescription);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
